__source__ = "https://stackoverflow.com/questions/50777688/finding-contours-with-lines-of-text-in-opencv"

import cv2
import os


def get_contours(image_path, image_name, flag_image_path = "flag_images", flag_image_name=None):
    image = cv2.imread(os.path.join(image_path, image_name))
    height, width, _ = image.shape
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  

    #--- performing Otsu threshold ---
    ret, thresh1 = cv2.threshold(gray, 0, 255,cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)

    #--- choosing the right kernel
    #--- kernel size of 3 rows (to join dots above letters 'i' and 'j')
    #--- and 10 columns to join neighboring letters in words and neighboring words
    rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 3))
    dilation = cv2.dilate(thresh1, rect_kernel, iterations = 1)

    #---Finding contours ---
    _, contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    im2 = image.copy()
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        # cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 1)
        for i in range(x, x+w):
            for j in range(y, y+h):
                image[j][i] = [0, 0, 255]
    if flag_image_name == None:
        flag_image_name = ".".join(image_name.split(".")[:-1]) + "_flag.png"
    cv2.imwrite(os.path.join(flag_image_path, flag_image_name), image)

    return os.path.join(flag_image_path, flag_image_name)

if __name__ == "__main__":
    get_contours(image_path="images", image_name="gakki_eng_Page1.png")